// pages/goods-detail/comps/bottom-tool.js
import { regeneratorRuntime } from '../../../utils/runtime.js'
import {  collectGoods } from '../../../service/public.js'

import {
	getSetting,
	chooseAddress,
	openSetting,
	showModal,
	showToast,
} from '../../../utils/asyncWX.js'

Component({
	/**
	 * 组件的属性列表
	 */
	properties: {
		gid: {
			type: Number,
			value: 0,
		},
	},
	ready() {
		// setTimeout(()=>{
		this.setData({
			userData: wx.$user.userInfo,
		})
		this.getFollow()
		// },500)
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		userData: null,
		isFollow: false,
	},
	options: {
		addGlobalClass: true,
	},
	/**
	 * 组件的方法列表
	 */
	methods: {
		addCart() {
			this.triggerEvent('addCart')
		},
		follow() {
			const follows = wx.getStorageSync('follows') || []
			const index = follows.findIndex((v) => v === this.data.gid)

			if (index !== -1) {
				follows.splice(index, 1)
				showToast({ title: '已取消关注' })
        wx.setStorageSync('follows', follows)
        this._collectGoods(false)
				this.getFollow()
			} else {
        follows.push(this.data.gid)
        this._collectGoods(true)
        
				showToast({ title: '关注成功' })
				wx.setStorageSync('follows', follows)
				this.getFollow()
			}
		},
		async getUserData(e) {
			const { userInfo } = e.detail
			if (!userInfo) {
				return await showToast({ title: '授权失败，请重新授权' })
			}

			wx.$user.setUserInfo(userInfo)

			this.setData({
				userData: userInfo,
			})
		},
		setUserInfo() {
			const userInfo = wx.getStorageSync('userInfo')

			this.setData({
				userInfo,
			})
		},
		getFollow() {
			const follows = wx.getStorageSync('follows') || []
			if (follows.find((v) => v === this.data.gid)) {
				this.setData({
					isFollow: true,
				})
			} else {
				this.setData({
					isFollow: false,
				})
			}
		},
		buy() {
			wx.navigateTo({
				url: '/pages/checkOrder/checkOrder?gid=' + this.data.gid,
			})
		},
		// 用户收藏的时候，发送给服务器的消息
		_collectGoods(collect) {
			console.log('我被触发了')
			collectGoods({
				openid: wx.getStorageSync('openid') || '',
				gid:this.data.gid,
				collect,
			}).then((res) => {
				console.log(res)
			})
		},
	},
})
